package com.asyf.provider.common.tcc;

import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author yjz
 * @Date 2022/2/9 9:40
 * <p>
 * 参考：https://wanght.blog.csdn.net/article/details/107702760
 * 官网demo：https://github.com/seata/seata-samples/tree/master/tcc/springboot-tcc-sample
 */
@Service
@Slf4j
public class FirstActionImpl implements FirstAction {

    @Autowired
    private NamedParameterJdbcTemplate jdbc;

    @Override
//    @Transactional //加上也不会先提交
    public boolean prepare(BusinessActionContext businessActionContext, int id) {
        String sql = "SELECT * FROM EMP where EMPNO = :empno";
        Map<String, Object> param = new HashMap<>();
        //插入
//        sql = "insert into EMP (EMPNO) VALUES (:empno)";
//        param.put("empno", 1111);
//        jdbc.update(sql, param);
        insertOracleComp();

        //模拟第一阶段失败
//        int b = 1;
//        b = b / a;

        //事务成功，保存一个标识，供第二阶段进行判断
        ResultHolder.setResult(getClass(), businessActionContext.getXid(), "p");
        log.info("FirstAction prepare成功{}", businessActionContext.getXid());
        return true;
    }

    @Override
//    @Transactional
    public boolean commit(BusinessActionContext businessActionContext) {
        log.info("FirstAction第二阶段提交,xid:{}", businessActionContext.getXid());

        // 防止幂等性，如果commit阶段重复执行则直接返回
        if (ResultHolder.getResult(getClass(), businessActionContext.getXid()) == null) {
            return true;
        }
        //提交成功是删除标识
        ResultHolder.removeResult(getClass(), businessActionContext.getXid());
        log.info("事务提交{}", businessActionContext.getXid());
        return true;
    }

    @Override
//    @Transactional
    public boolean rollback(BusinessActionContext businessActionContext) {
        log.info("FirstAction第二阶段事务回滚,xid:{}", businessActionContext.getXid());
        //第一阶段没有完成的情况下，不必执行回滚
        //幂等性控制：如果重复执行回滚则直接返回
        if (ResultHolder.getResult(getClass(), businessActionContext.getXid()) == null) {
            return true;
        }
        //自定义业务：回滚需要执行的操作
        String sql = "delete from TEST where id = :id";
        Map<String, Object> param = new HashMap<>();
        param.put("id", 1111);
        int update = jdbc.update(sql, param);
        log.info("update:{}", update);

        //回滚结束时，删除标识
        ResultHolder.removeResult(getClass(), businessActionContext.getXid());
        return true;
    }

    private void insertOracleComp() {
        String sql = "insert into TEST (ID,NAME) VALUES (:id,'张三')";
        Map<String, Object> param = new HashMap<>();
        param.put("id", 1111);
        jdbc.update(sql, param);
    }
}
